package com.ts.api.module.channel.controller;

import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.date.DateUtils;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.ts.api.common.constant.BizEnum;
import com.ts.api.common.context.ChannelContext;
import com.ts.api.common.context.ChannelRequestContext;
import com.ts.api.common.context.ChannelUserContext;
import com.ts.api.common.entity.AjaxResult;
import com.ts.api.exp.BizException;
import com.ts.api.module.channel.entity.cache.ChannelCacheUser;
import com.ts.api.module.channel.entity.po.ChannelFormFieldPO;
import com.ts.api.module.channel.entity.po.ChannelUserFormFieldPO;
import com.ts.api.module.channel.entity.po.ChannelUserFormPO;
import com.ts.api.module.channel.entity.vo.ReqChannelFormVO;
import com.ts.api.module.channel.entity.vo.RespChannelFormFieldValueVO;
import com.ts.api.module.channel.service.ChannelFormService;
import com.ts.api.module.channel.service.DoubleWriteUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 动态表单字段Controller
 *
 * @author ghb
 * @date 2023-09-20
 */
@RestController
@RequestMapping("/channel/form")
public class ChannelFormController {

    @Autowired
    private ChannelFormService channelFormService;
    @Autowired
    private DoubleWriteUserService doubleWriteUserService;

    /**
     * 根据渠道查询动态表单字段列表
     */
    @GetMapping("/list")
    public AjaxResult list() {
        List<ChannelFormFieldPO> list = channelFormService.listByChannelId(ChannelContext.getId());
        List<RespChannelFormFieldValueVO> listVO = RespChannelFormFieldValueVO.convertVO(list);

        String[] mappingName = new String[] {"realEstateInfo", "carInfo", "providentFund", "socialSecurity", "overdue"};
        String getTableFlow = ChannelRequestContext.getTableFlow();
        //  第一个表单页面过滤
        if ("1".equals(getTableFlow)) {
            //  合并VO
            Map<String, List<RespChannelFormFieldValueVO>> margeMap = MapUtils.newLinkedHashMap();

            margeMap.put("first", RespChannelFormFieldValueVO.convertVO(CollUtils.find(list, t -> !Eq.strOr(t.getMappingName(), mappingName))));

            //  合并
            List<ChannelFormFieldPO> copyList = CopyUtils.copyList(list, ChannelFormFieldPO.class);
            CollUtils.filter(copyList, t -> Eq.strOr(t.getMappingName(), "sesameCredit", "overdue"));
            margeMap.put("second", RespChannelFormFieldValueVO.convertVO(copyList));

            margeMap.put("third", RespChannelFormFieldValueVO.convertVO(CollUtils.find(list, t -> t.getMappingName().equals("overdue"))));
            return AjaxResult.success(margeMap);
        }
        return AjaxResult.success(listVO);
    }

    /**
     *  获取用户已填写的表单信息
     */
    @GetMapping("/getForm")
    public AjaxResult getForm() {
        List<ChannelUserFormFieldPO> list = channelFormService.listUserFormField();
        return AjaxResult.success(list);
    }

    /**
     * 插入用户表单
     *
     * @param listVO
     * @param request
     * @return
     */
    @PostMapping("/insert")
    public AjaxResult insert(@RequestBody List<ReqChannelFormVO> listVO, HttpServletRequest request) {
        ChannelCacheUser channelCacheUserBO = ChannelUserContext.get();
        Long channelId = ChannelContext.getId();

        //  检测参数
        channelFormService.checkFormParam(listVO);

        //  插入用户表单信息
        List<ChannelUserFormPO> listUserForm = CollUtils.newArrayList();
        listVO.forEach(t -> {
            ChannelUserFormPO userFormPO = new ChannelUserFormPO();
            userFormPO.setUserId(channelCacheUserBO.getUserId());
            userFormPO.setChannelId(channelId);
            userFormPO.setFormFieldId(t.getFieldId());
            userFormPO.setFormFieldValueId(t.getFieldValueId());
            userFormPO.setCreateTime(DateUtils.currentTime());
            listUserForm.add(userFormPO);
        });

        try {
            doubleWriteUserService.removeByUserId(channelCacheUserBO.getUserId());
            doubleWriteUserService.batchInsertUserForm(listUserForm);
        } catch (DuplicateKeyException e) {
            BizException.fastFail(BizEnum.FORM_DUPLICATE);
        }
        return AjaxResult.success("提交成功");
    }

}
